<template>
  <!-- 空组件，无界面展示 -->
  <view style="display: none;" :prop="src" :change:prop="canvas.getVideoCanvas"/>
</template>

<script >
export default {
  name: 'VideoCover',

  props: {
    videoUrl: {
      type: String,
      required: true
    }
  },

  data() {
    return {
      src: '',
	  timer:null
    }
  },

  watch: {
    videoUrl: {
      immediate: true,
      handler(val) {
        if (val) {
          uni.showLoading({
			  complete:()=>{
				  this.timer = setTimeout(()=>{
					  uni.hideLoading()
				  },1000)
			  }
		  })
          this.src = val
        }
      }
    }
  },

  methods: {
    // 提供给 renderjs 调用
    getVideoCover({ cover }) {
	  clearTimeout(this.timer)
	  uni.hideLoading()
	  this.base64ToTempFile(cover,'cover',(tempImage)=>{
		  this.$emit('cover', tempImage)
	  })
    },
	base64ToTempFile(base64Str, fileNamePrefix = 'tempImage', callback) {
	  const timestamp = Date.now();
	  const fileName = `${fileNamePrefix}_${timestamp}.png`;
	
	  const bitmap = new plus.nativeObj.Bitmap('tempBitmap');
	  bitmap.loadBase64Data(base64Str, () => {
	    const path = `_doc/${fileName}`;
	    bitmap.save(path, {}, res => {
	      callback(res.target);
	      bitmap.clear();
	    }, err => {
	      console.error('保存失败', err);
	    });
	  }, err => {
	    console.error('base64 加载失败', err);
	  });
	}
  }
}
</script>

<script module="canvas" lang="renderjs">
export default {
  methods: {
    getVideoCanvas(newVal, oldVal, instance) {
		console.log('111',newVal)
      if (!newVal) return
      const video = document.createElement('video')
      video.src = newVal
      video.crossOrigin = 'anonymous'
      video.preload = 'auto'
      video.muted = true

      // 设置截图时间
      video.addEventListener('loadedmetadata', () => {
        video.currentTime = 0.1
      })

      video.addEventListener('seeked', () => {
		  setTimeout(()=>{
			const canvas = document.createElement('canvas')
			canvas.width = video.videoWidth
			canvas.height = video.videoHeight
			const ctx = canvas.getContext('2d')
			ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
			const imgSrc = canvas.toDataURL('image/jpeg')
			// 通知逻辑层
			this.$ownerInstance.callMethod('getVideoCover', {
			  cover: imgSrc
			})
			// 清理 DOM，防止内存泄露
			video.src = ''
			video.remove()
			canvas.remove()
		  }, 500);
      })

      // 若出错也清除资源
      video.addEventListener('error', (err) => {
		  console.log()
		  console.log('error',err)
        video.remove()
      })
    }
  }
}
</script>
